package com.example.zookeeper.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.zookeeper.common.constant.Contants;
import com.example.zookeeper.config.kafka.KafkaSender;
import com.example.zookeeper.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping(value = "/kafka")
public class KafkaSenderController {

    @Autowired
    private KafkaSender kafkaSender;

    @Value("#{'${kafka.listener.topics}'.split(',')}")
    private List<String> topics;

    @GetMapping(value = "/message/sending")
    public User sendMessage() {
        int id = new Random().nextInt(20);
        User user = new User();
        user.setId(id);
        user.setUserName("HS-" + System.currentTimeMillis());
        user.setDescription("text");
        user.setCreateTime(LocalDateTime.now());
        String JSONUser = JSON.toJSONStringWithDateFormat(user,
                Contants.DateTimeFormat.DATE_TIME_PATTERN, //日期格式化
                SerializerFeature.PrettyFormat); //格式化json
        kafkaSender.sendMessage(topics.get(0), String.valueOf(id), JSONUser);
        return user;
    }

}
